package com.ruoyi.project.system.controller;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.domain.SysDistribution;
import com.ruoyi.project.system.domain.SysOrder;
import com.ruoyi.project.system.domain.vo.AutoOutVo;
import com.ruoyi.project.system.domain.vo.InAndOutVo;
import com.ruoyi.project.system.service.ISysDistributionService;
import com.ruoyi.project.system.service.ISysGoodsService;
import com.ruoyi.project.system.service.ISysOrderService;
import com.ruoyi.project.system.service.ISysStockService;
import com.ruoyi.quartz.task.json.OrderGoods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * 出库任务Controller
 *
 * @author orange
 * @date 2022-04-09
 */
@RestController
@RequestMapping("/system/distribution")
public class SysDistributionController extends BaseController {
  @Autowired private ISysDistributionService sysDistributionService;
  @Autowired private ISysOrderService orderService;
  @Autowired private ISysStockService sysStockService;
  @Autowired private ISysGoodsService goodsService;
  /** 查询出库任务列表 */
  @PreAuthorize("@ss.hasPermi('system:distribution:list')")
  @GetMapping("/list")
  public TableDataInfo list(SysDistribution sysDistribution) {
    startPage();
    List<SysDistribution> list = sysDistributionService.selectSysDistributionList(sysDistribution);
    return getDataTable(list);
  }

  /** 导出出库任务列表 */
  @PreAuthorize("@ss.hasPermi('system:distribution:export')")
  @Log(title = "出库任务", businessType = BusinessType.EXPORT)
  @PostMapping("/export")
  public void export(HttpServletResponse response, SysDistribution sysDistribution) {
    List<SysDistribution> list = sysDistributionService.selectSysDistributionList(sysDistribution);
    ExcelUtil<SysDistribution> util = new ExcelUtil<SysDistribution>(SysDistribution.class);
    util.exportExcel(response, list, "出库任务数据");
  }

  /** 获取出库任务详细信息 */
  @PreAuthorize("@ss.hasPermi('system:distribution:query')")
  @GetMapping(value = "/{distributionId}")
  public AjaxResult getInfo(@PathVariable("distributionId") Long distributionId) {
    return AjaxResult.success(
        sysDistributionService.selectSysDistributionByDistributionId(distributionId));
  }

  /** 新增出库任务 */
  @PreAuthorize("@ss.hasPermi('system:distribution:add')")
  @Log(title = "出库任务", businessType = BusinessType.INSERT)
  @PostMapping
  public AjaxResult add(@RequestBody SysDistribution sysDistribution) {
    return toAjax(sysDistributionService.insertSysDistribution(sysDistribution));
  }

  /** 修改出库任务 */
  @PreAuthorize("@ss.hasPermi('system:distribution:edit')")
  @Log(title = "出库任务", businessType = BusinessType.UPDATE)
  @PutMapping
  public AjaxResult edit(@RequestBody SysDistribution sysDistribution) {
    return toAjax(sysDistributionService.updateSysDistribution(sysDistribution));
  }

  /** 删除出库任务 */
  @PreAuthorize("@ss.hasPermi('system:distribution:remove')")
  @Log(title = "出库任务", businessType = BusinessType.DELETE)
  @DeleteMapping("/{distributionIds}")
  public AjaxResult remove(@PathVariable Long[] distributionIds) {
    return toAjax(sysDistributionService.deleteSysDistributionByDistributionIds(distributionIds));
  }

  @Log(title = "出库任务", businessType = BusinessType.DISTRIBUTION_FINISH)
  @PreAuthorize("@ss.hasPermi('system:distribution:distribution')")
  @PostMapping("/goOut")
  @Transactional
  public AjaxResult goOut(@RequestBody AutoOutVo autoOutVo) {
    SysDistribution sysDistribution = new SysDistribution();
    sysDistribution.setDistributionStatus(1);
    // 获取订单信息
    SysOrder sysOrder = orderService.selectSysOrderByOrderId(autoOutVo.getOrderId());
    // 获取商品信息
    List<OrderGoods> orderGoods = JSON.parseArray(sysOrder.getGoodsList(), OrderGoods.class);
    // 减少库存
    orderGoods.forEach(
        item -> {

          // 减少商品的数量
          goodsService.reduceStore(item.getGoodsId(), (long) item.getNum());

          // 减少库存的数量
          InAndOutVo inAndOutVo = new InAndOutVo();
          inAndOutVo.setNum((long) item.getNum());
          inAndOutVo.setPicture("");
          inAndOutVo.setStockId(item.getStockId());
          inAndOutVo.setUserId(autoOutVo.getUserId());
          inAndOutVo.setRecordType(2);

          try {
            sysStockService.inAndOutWarehouse(inAndOutVo);
          } catch (ServiceException e) {
            System.out.println("库存不足");
            sysOrder.setOrderStatus(6L);
            sysDistribution.setDistributionStatus(2);
            orderService.updateSysOrder(sysOrder);
          }
        });

    // 修改状态
    sysOrder.setOrderStatus(5L);
    orderService.updateSysOrder(sysOrder);

    // 修复配送任务状态
    sysDistribution.setDistributionId(autoOutVo.getDistributionId());
    sysDistribution.setDealPerson(autoOutVo.getUserId());
    sysDistribution.setUpdateTime(new Date());
    sysDistributionService.updateSysDistribution(sysDistribution);

    return success();
  }
}
